package com.haotian.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class _ResponseUtils {

	private static final String RETURN_CODE = "return_code";
	private static final String RETURN_MSG = "return_msg";
	private static final String ContentType_JSON = "application/json;charset=utf-8";
	private static final String ContentType_Plain = "text/plain";

	/**
	 * 快速返回一个处理结果 JSON形式
	 * 
	 * { "return_code":"code", "return_msg":"msg" }
	 * 
	 * @param resp
	 * @param msg
	 * @param code
	 * @throws IOException
	 */
	public static void printJsonMsg(HttpServletResponse resp, String msg, String code) throws IOException {
		JSONObject json = new JSONObject();
		json.put(RETURN_CODE, code);
		json.put(RETURN_MSG, msg);
		printJSON(resp, json.toJSONString());
	}

	/**
	 * 把任意对象以json形式返回
	 */
	public static void printJsonMsg(HttpServletResponse resp, Object object) throws IOException {
		printJSON(resp, JSON.toJSONString(object));
	}

	/**
	 * 向流中返回json数据结果 本方法只做返回String
	 * 
	 * 不做装箱拆箱操作 需要拆箱或装箱需要在外部完成后调用本方法
	 * 
	 * @param resp
	 * @param msg
	 * @throws IOException
	 */
	private static void printJSON(HttpServletResponse resp, String msg) throws IOException {
		resp.setContentType(ContentType_JSON);
		try(PrintWriter writer = resp.getWriter();){
			writer.print(msg);
			writer.close();
		}
	}

	/**
	 * 以plain 形式写出字符
	 * 
	 * @param resp
	 * @param msg
	 * @throws IOException
	 */

	public static void printPlain(HttpServletResponse resp, String msg) throws IOException {
		resp.setContentType(ContentType_Plain);
		try(PrintWriter writer = resp.getWriter();){
			writer.print(msg);
			writer.close();
		}
	}

}
